package com.yy.view.freemarker;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import org.apache.log4j.Logger;

import com.jagregory.shiro.freemarker.ShiroTags;
import com.yy.utils.PropertiesUtil;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * FreeMarker
 * 
 * @author 
 *
 */
public class FreeMarkerUtil {

	private static Logger log = Logger.getLogger(FreeMarkerUtil.class);
	private static Configuration cfg = null;

	/**
	 * 读取模板内容
	 * 
	 * @param pageName
	 *            页面模板名称
	 * @param dataModel
	 *            模板所需数据
	 * @return
	 */
	public static String getTemplateContent(String pageName, Map<String, Object> dataModel) {
		Configuration cfg = null;
		Template temp = null;
		Writer out = null;
		try {
			cfg = new Configuration();
			String contextPath=PropertiesUtil.getFreemarkerTemplatePath();
			cfg.setDirectoryForTemplateLoading(new File(contextPath));
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			cfg.setLocale(Locale.CHINA);
			// cfg.setSharedVariable("xxxUtil", new XXXUtil());//自定义方法供调用
			cfg.setSharedVariable("shiro", new ShiroTags());
			cfg.setDefaultEncoding("utf-8");
			cfg.setClassicCompatible(true);// 处理空值为空字符串
			temp = cfg.getTemplate(pageName);
			out = new StringWriter(2048);
			temp.process(dataModel, out);
			return out.toString();
		} catch (IOException e) {
			e.printStackTrace();
			log.error("###Read freemarker error, pageName is: " + pageName);
		} catch (TemplateException e) {
			e.printStackTrace();
			log.error("###Read freemarker error, pageName is: " + pageName);
		}finally{
			try {
				if(out!=null)out.flush();
				if(out!=null)out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

}
